package com.sibco.client.common;

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;

public class XMLUtil {

	public static Node getNextSiblingElement(Node node, String attrName) {
		Node next = getNextSiblingElement(node);
		while (null != next) {
			if (getNodeAttributeValue(next, attrName)
				.equals(getNodeAttributeValue(node, attrName))) {
				return next;
			}
			next = getNextSiblingElement(next);
		}
		return null;
	}

	public static Node getNextChildElement(Node node) {
		Node childNode = node.getFirstChild();
		while (null != childNode) {
			if (childNode.getNodeType() == Node.ELEMENT_NODE) {
				return childNode;
			}
			childNode = childNode.getNextSibling();
		}
		return null;
	}

	public static Node getNextSiblingElement(Node node) {
		Node siblingNode = node.getNextSibling();
		while (null != siblingNode) {
			if (siblingNode.getNodeType() == Node.ELEMENT_NODE) {
				return siblingNode;
			}
			siblingNode = siblingNode.getNextSibling();
		}
		return null;
	}

	public static String getNodeAttributeValue(Node node, String attrName) {
		try {
			NamedNodeMap attrs = node.getAttributes();
			Node attrNode = attrs.getNamedItem(attrName);
			return attrNode.getNodeValue();
		} catch (NullPointerException e) {
			return "";
		}
	}

	public static String getNodeTextValue(Node node) {
		try {
			Node childNode = node.getFirstChild();
			while (null != childNode) {
				if (childNode.getNodeType() == Node.TEXT_NODE) {
					return childNode.getNodeValue();
				}
				childNode = childNode.getNextSibling();
			}
		} catch (NullPointerException e) {
		}
		return null;
	}

	public static Document loadConfig(String fileName)
		throws SAXException, ParserConfigurationException, IOException {
		DocumentBuilderFactory docBuilderFactory =
			DocumentBuilderFactory.newInstance();
		DocumentBuilder parser = docBuilderFactory.newDocumentBuilder();
		return parser.parse(new File(fileName));
	}
}
